import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import javax.sound.sampled.*;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class C extends JFrame implements ActionListener {
    private JPanel north, center;
    private JTextField field;
    private JButton[] btns;
    private String firstNumber = "";
    private String operation = "";
    private boolean startNewNumber = true;
    
    // 可爱风格配色
    private Color BG_COLOR = new Color(255, 230, 240);
    private Color BTN_COLOR = new Color(255, 200, 220);
    private Color SPECIAL_BTN_COLOR = new Color(255, 150, 180);
    private Color TEXT_COLOR = new Color(100, 50, 80);

    private void initComponent() {
        getContentPane().setBackground(BG_COLOR);
        setLayout(new BorderLayout(10, 10));
        
        // 顶部显示区域
        north = new JPanel(new BorderLayout());
        north.setBackground(BG_COLOR);
        north.setBorder(new EmptyBorder(15, 15, 10, 15));
        
        field = new JTextField();
        field.setPreferredSize(new Dimension(400, 100));
        field.setEditable(false);
        field.setFont(new Font("Comic Sans MS", Font.BOLD, 36));
        field.setForeground(TEXT_COLOR);
        field.setBackground(new Color(255, 245, 250));
        field.setBorder(new RoundBorder(20, new Color(255, 180, 200)));
        field.setHorizontalAlignment(JTextField.RIGHT);
        north.add(field, BorderLayout.CENTER);
        
        // 底部装饰
        JLabel decoration = new JLabel("✧･ﾟ: *✧･ﾟ:* 可爱计算器 *:･ﾟ✧*:･ﾟ✧");
        decoration.setFont(new Font("Comic Sans MS", Font.PLAIN, 14));
        decoration.setForeground(new Color(255, 120, 150));
        decoration.setHorizontalAlignment(SwingConstants.CENTER);
        north.add(decoration, BorderLayout.SOUTH);
        
        // 按钮区域
        center = new JPanel(new GridLayout(5, 4, 10, 10));
        center.setBackground(BG_COLOR);
        center.setBorder(new EmptyBorder(10, 15, 15, 15));
        
        String[] btnLabels = {
            "AC", "B", "S", "÷", 
            "7", "8", "9", "×", 
            "4", "5", "6", "-", 
            "1", "2", "3", "+", 
            "00", "0", ".", "="
        };
        
        btns = new JButton[btnLabels.length];
        for (int i = 0; i < btnLabels.length; i++) {
            btns[i] = createCuteButton(btnLabels[i]);
            btns[i].addActionListener(this);
            center.add(btns[i]);
        }
        
        add(north, BorderLayout.NORTH);
        add(center, BorderLayout.CENTER);
        
       
    }
    
    private JButton createCuteButton(String text) {
        JButton btn = new JButton(text);
        btn.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
        btn.setFocusPainted(false);
        btn.setContentAreaFilled(false);
        btn.setOpaque(true);
        
        if (text.matches("[0-9.]")) {
            btn.setBackground(BTN_COLOR);
        } else if (text.equals("=")) {
            btn.setBackground(new Color(255, 120, 150));
            btn.setForeground(Color.WHITE);
        } else if (text.equals("S")) {
            btn.setBackground(new Color(255, 100, 130));
            btn.setForeground(Color.WHITE);
        } else {
            btn.setBackground(SPECIAL_BTN_COLOR);
        }
        
        btn.setForeground(TEXT_COLOR);
        btn.setBorder(new RoundBorder(15, new Color(255, 180, 200)));
        
        btn.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                btn.setBackground(btn.getBackground().darker());
            }
            public void mouseExited(MouseEvent e) {
                if (text.matches("[0-9.]")) {
                    btn.setBackground(BTN_COLOR);
                } else if (text.equals("=")) {
                    btn.setBackground(new Color(255, 120, 150));
                } else if (text.equals("S")) {
                    btn.setBackground(new Color(255, 100, 130));
                } else {
                    btn.setBackground(SPECIAL_BTN_COLOR);
                }
            }
        });
        
        return btn;
    }
    
    class RoundBorder extends AbstractBorder {
        private int radius;
        private Color color;
        
        public RoundBorder(int radius, Color color) {
            this.radius = radius;
            this.color = color;
        }
        
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            Graphics2D g2 = (Graphics2D)g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(color);
            g2.drawRoundRect(x, y, width-1, height-1, radius, radius);
            g2.dispose();
        }
        
        public Insets getBorderInsets(Component c) {
            return new Insets(radius/2, radius/2, radius/2, radius/2);
        }
    }
    
   
    
    private String getCurrentNumber(String expression) {
        if (expression.isEmpty()) return "";
        
        int i = expression.length() - 1;
        while (i >= 0) {
            char c = expression.charAt(i);
            if (isOperator(c) || c == ' ') {
                break;
            }
            i--;
        }
        return expression.substring(i + 1);
    }
    
    private void setBtnText(String text) {
        String oldText = field.getText();
        
        switch (text) {
            case "AC":
                field.setText("");
                 System.out.println("0");
                break;
                
            case "B":
                if (!oldText.isEmpty()) {
                    field.setText(oldText.substring(0, oldText.length()-1));
                }
                break;
                
            case "S":
                if (!oldText.isEmpty()) {
                    try {
                        double num = Double.parseDouble(oldText);
                        field.setText(String.valueOf(num * num));
                        startNewNumber = true;
                    } catch (NumberFormatException e) {
                        field.setText("Error");
                    }
                }
                break;
                
            case "=":
                calculate();
                break;
                
            case ".":
                if (oldText.isEmpty()) {
        // 如果完全为空，补0
        field.setText("0.");
        startNewNumber = false;
    } 
    else {
        char lastChar = oldText.charAt(oldText.length() - 1);
        if (isOperator(lastChar)) {
            // 运算符后直接按小数点，补0
            field.setText(oldText + "0.");
            startNewNumber = false;
        }
        else if (lastChar == '.') {
            // 已经有点号，忽略输入
            return;
        }
        else {
            // 检查当前数字是否已有小数点
            String currentNumber = getCurrentNumber(oldText);
            if (!currentNumber.contains(".")) {
                // 当前数字没有小数点，可以添加
                field.setText(oldText + ".");
                startNewNumber = false;
            }
            // 已有小数点则不处理
        }
    }
                break;
                
            case "+":
            case "-":
            case "×":
            case "÷":
                if (oldText.length() > 0 && isOperator(oldText.charAt(oldText.length() - 1))) {
                    field.setText(oldText.substring(0, oldText.length() - 1) + text);
                } else {
                    field.setText(oldText + text);
                }
                startNewNumber = true;
                break;
                
            default: // 数字
               
            field.setText(oldText + text);
                
        }
    }
    
    private void calculate() {
        String expression = field.getText()
                .replace("×", "*")
                .replace("÷", "/");
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("javascript");
        try{
            Object result = engine.eval(expression);
            field.setText(result.toString());
        
        } catch (ScriptException e) {
            field.setText("Error");
            //startNewNumber = true;
            e.printStackTrace();
        }
    }
    private boolean isOperator(char c) {
    return c == '+' || c == '-' || c == '×' || c == '÷';
}




    @Override
    public void actionPerformed(ActionEvent e) {
       
        String command = ((JButton)e.getSource()).getText();
        setBtnText(command);
    }
    
    public C() {
        setTitle("✿ 可爱计算器 ✿");
        setSize(400, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        initComponent();
        setVisible(true);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new C());
    }
}